﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MaxLeaf.Common;
using System.Data;
using MaxLeaf.DB;

namespace MaxLeaf.DAL
{
    public class GetOnHand
    {
        public double GetQtyOnHand(string strDBName, string strFitemID, string strMDCFItemID, string strMeasureUnitFItemID)
        {
            double dblQty = 0;
            DBAccess dbcon = new DBAccess(ServerInfo.GetK3ServerByDBName(strDBName));
            DBAccess dbK3Master =  new DBAccess (ServerInfo.GetK3MasterServer());
            string strOrder_Unit_ID = new K2K.t_MeasureUnitDAL().GetDestMapKeyValue(dbK3Master, dbcon, strMeasureUnitFItemID);
            string strSQL = @" select sum(i1.Fqty) as Qty,i1.fitemid                        from  icinventory i1                        inner join t_item t1 on i1.fstockid=t1.fitemid                        inner join t_item t2 on t1.fnumber=t2.fnumber                          where t2.fitemclassid=1 and t2.fitemid='{0}' and i1.fitemid='{1}'
                        group by i1.fitemid ";
            strSQL = string.Format(strSQL, strMDCFItemID, strFitemID);
            DataRow drQty = dbcon.GetDataFirstRow(strSQL);
            if (drQty != null)
            {
                dblQty = CvtFunc.ToDouble(drQty["Qty"]);
            }
            else
            {
                dblQty = 0;
            }

            double dblRate = 0;
            strSQL = " select B.Fmeasureunitid,b.Fcoefficient from t_icItem A inner join t_measureunit B on A.FunitGroupID= B.FunitGroupID and ";
            strSQL += " A.FItemID='" + strFitemID + "'  ";
            strSQL += " and B.Fmeasureunitid='" + strOrder_Unit_ID + "'";
            DataRow drRate = dbcon.GetDataFirstRow(strSQL);
            if (drRate != null)
            {
                dblRate = CvtFunc.ToDouble(drRate["Fcoefficient"]);
            }
            else
            {
                dblRate = 1;
            }
            dblQty =Math.Round(dblQty / dblRate,0);
            return dblQty;
        }
    }
}
